package com.coolweather.android.fragment;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.coolweather.android.activity.MainActivity;
import com.coolweather.android.activity.R;
import com.coolweather.android.activity.WeatherActivity;
import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;
import com.coolweather.android.gson.Utility;
import com.coolweather.android.util.AplicationUtils;
import com.coolweather.android.util.HttpUtil;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/12/13 0013.
 */

public class ChooseFragment extends Fragment{
    public static final int level_provice = 0;
    public static final int level_city = 1;
    public static final int level_county = 2;
    private ProgressDialog progressDialog;
    private TextView textView;
    private Button button;
    private ListView listView;
    private ArrayAdapter<String> arrayAdapter;
    private List<String> dataList;
    private List<Province> provices;
    private List<City> citys;
    private List<County> counties;
    private Province selectProvice;
    private City selectCity;
    private County selectCounty;
    private int currentLevel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area,container,false);
        textView = (TextView)view.findViewById(R.id.title_text);
        button = (Button)view.findViewById(R.id.back);
        listView = (ListView)view.findViewById(R.id.listview);
        dataList= new ArrayList<>();
        arrayAdapter = new ArrayAdapter<String>(AplicationUtils.getContext(),android.R.layout.simple_list_item_1,dataList);
        listView.setAdapter(arrayAdapter);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentLevel==level_provice){
                    selectProvice=provices.get(position);
                    queryCities();
                }else if (currentLevel==level_city){
                    selectCity=citys.get(position);
                    queryCounties();
                }else if (currentLevel==level_county){
                    String weatherId = counties.get(position).getWeatherId();
                    if (getActivity() instanceof MainActivity) {
                        Intent intent = new Intent(getActivity(), WeatherActivity.class);
                        intent.putExtra("weather_id", weatherId);
                        startActivity(intent);
                        getActivity().finish();
                    }else if (getActivity() instanceof WeatherActivity){
                        WeatherActivity activity = (WeatherActivity) getActivity();
                        activity.drawerLayout.closeDrawers();
                        activity.swipeRefreshLayout.setRefreshing(true);
                        activity.requestWeather(weatherId);
                    }
                }
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentLevel==level_county){
                    queryCities();
                }else if(currentLevel==level_city){
                    queryProvices();
                }
            }
        });
        queryProvices();
    }
    private void queryProvices(){
        textView.setText("中国");
        button.setVisibility(View.GONE);
        provices = DataSupport.findAll(Province.class);
        if (provices.size()>0){
            dataList.clear();
            for (Province p : provices){
                dataList.add(p.getProvinceName());
            }
            arrayAdapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = level_provice;
        }else{
            String address="http://guolin.tech/api/china";
            queryFromServer(address,"province");
        }
    }

    private void queryCities(){
        textView.setText(selectProvice.getProvinceName());
        button.setVisibility(View.VISIBLE   );
        citys = DataSupport.where("provinceId=?",String.valueOf(selectProvice.getId())).find(City.class);
        if (citys.size()>0){
            dataList.clear();
            for (City c : citys){
                dataList.add(c.getCityName());
            }
            arrayAdapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = level_city;
        }else{
            int provinceCode = selectProvice.getProvinceCode();
            String address="http://guolin.tech/api/china/"+provinceCode;
            queryFromServer(address,"city");
        }
    }

    private void queryCounties(){
        textView.setText(selectCity.getCityName());
        button.setVisibility(View.VISIBLE);
        counties = DataSupport.where("cityId=?",String.valueOf(selectCity.getId())).find(County.class);
        if (counties.size()>0){
            dataList.clear();
            for (County c : counties){
                dataList.add(c.getCountyName());
            }
            arrayAdapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = level_county;
        }else{
            int cityCode = selectCity.getCityCode();
            String address="http://guolin.tech/api/china/"+selectProvice.getProvinceCode()+"/"+cityCode;
            queryFromServer(address,"county");
        }
    }

    private void queryFromServer(String address,final String type){
        showProgressDialog();
        HttpUtil.setOkHttpRequest(address, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(AplicationUtils.getContext(),"加载失败！",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resultText = response.body().string();
                boolean result = false;
                if ("province".equals(type)){
                    result = Utility.handleProviceData(resultText);
                }else if("city".equals(type)){
                    result =Utility.handleCityData(resultText,selectProvice.getId());
                }else if("county".equals(type)){
                    result=Utility.handleCountyData(resultText,selectCity.getId());
                }
                if (result){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)){
                                queryProvices();
                            }else if("city".equals(type)){
                                queryCities();
                            }else if("county".equals(type)){
                                queryCounties();
                            }
                        }
                    });

                }
            }
        });
    }

    private void showProgressDialog(){
        if (progressDialog==null){
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if (progressDialog!=null){
            progressDialog.dismiss();
        }
    }
}
